<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register Admin - RINT 数据分享平台</title>
    <link href="/static/bootstrap/bootstrap.min.css" rel="stylesheet">
    <link href="/static/style.css" rel="stylesheet">
    <link rel="icon" type="image/x-icon" href="/static/favicon.ico">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="/">RINT 数据分享平台</a>
            <div class="navbar-nav ms-auto" id="navbarNav">
                <!-- Navigation will be updated by JavaScript based on authentication state -->
            </div>
        </div>
    </nav>

    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h4 class="text-center">Register Admin User</h4>
                        <p class="text-center text-muted">This page can only be used to create the first admin user</p>
                    </div>
                    <div class="card-body">
                        <form id="registerForm">
                            <div class="mb-3">
                                <label for="email" class="form-label">Email</label>
                                <input type="email" class="form-control" id="email" required>
                            </div>
                            <div class="mb-3">
                                <label for="password" class="form-label">Password</label>
                                <input type="password" class="form-control" id="password" required>
                            </div>
                            <div class="mb-3">
                                <label for="confirmPassword" class="form-label">Confirm Password</label>
                                <input type="password" class="form-control" id="confirmPassword" required>
                            </div>
                            <button type="submit" class="btn btn-primary w-100">Register Admin</button>
                        </form>
                        <div id="message" class="mt-3"></div>
                    </div>
                </div>
                <div class="text-center mt-3">
                    <a href="/login">Already have an account? Login</a>
                </div>
            </div>
        </div>
    </div>

    <script>
        let authToken = localStorage.getItem('token');
        let currentUser = null;

        async function loadCurrentUser() {
            try {
                // Try server-side authentication first if no token
                if (!authToken) {
                    const serverResponse = await fetch('/api/user-info');
                    if (serverResponse.ok) {
                        currentUser = await serverResponse.json();
                        return;
                    }
                }
                
                // Fall back to token-based authentication
                const response = await fetch('/api/user-info', {
                    headers: authToken ? {
                        'Authorization': `Bearer ${authToken}`
                    } : {}
                });
                
                if (response.ok) {
                    currentUser = await response.json();
                    
                    // Store the token if we got a successful response without one
                    if (!authToken && response.headers.get('Authorization')) {
                        authToken = response.headers.get('Authorization').replace('Bearer ', '');
                        localStorage.setItem('token', authToken);
                    }
                } else {
                    // If token is invalid, clear it and continue as unauthenticated
                    if (authToken) {
                        localStorage.removeItem('token');
                        document.cookie = 'access_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC; SameSite=Lax';
                    }
                    currentUser = null;
                }
            } catch (error) {
                console.error('Error loading current user:', error);
                // If there's an error, continue as unauthenticated
                currentUser = null;
            }
        }

        function updateNavigation() {
            const navbarNav = document.getElementById('navbarNav');
            
            if (currentUser) {
                // User is logged in
                navbarNav.innerHTML = `
                    <a class="nav-link" href="/dashboard">数据仓库</a>
                    ${currentUser.is_admin ? '<a class="nav-link" href="/admin">Admin Panel</a>' : ''}
                    <div class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <span id="currentUserEmail">${currentUser.email}</span>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
                            <li><a class="dropdown-item" href="#" onclick="logout()">Logout</a></li>
                        </ul>
                    </div>
                `;
            } else {
                // User is not logged in
                navbarNav.innerHTML = `
                    <a class="nav-link" href="/login">Login</a>
                    <a class="nav-link" href="/register">Register</a>
                `;
            }
        }

        function logout() {
            localStorage.removeItem('token');
            // Clear the cookie as well
            document.cookie = 'access_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC; SameSite=Strict';
            window.location.reload();
        }

        // Initialize the page
        loadCurrentUser().then(() => {
            updateNavigation();
        }).catch(error => {
            console.error('Error in page initialization:', error);
            updateNavigation();
        });
    </script>

    <script src="/static/bootstrap/bootstrap.bundle.min.js"></script>
    <script>
        document.getElementById('registerForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const email = document.getElementById('email').value;
            const password = document.getElementById('password').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            const messageDiv = document.getElementById('message');
            
            if (password !== confirmPassword) {
                messageDiv.innerHTML = '<div class="alert alert-danger">Passwords do not match</div>';
                return;
            }
            
            try {
                const response = await fetch('/api/register-admin', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        email: email,
                        password: password
                    })
                });
                
                if (response.ok) {
                    messageDiv.innerHTML = '<div class="alert alert-success">Admin user created successfully! Redirecting to login...</div>';
                    setTimeout(() => {
                        window.location.href = '/login';
                    }, 2000);
                } else {
                    const error = await response.json();
                    messageDiv.innerHTML = `<div class="alert alert-danger">${error.detail || 'Registration failed'}</div>`;
                }
            } catch (error) {
                messageDiv.innerHTML = '<div class="alert alert-danger">Network error occurred</div>';
            }
        });
    </script>
</body>
</html>